package com.example.mghotel.ui.order;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.example.mghotel.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class OrderFragment extends Fragment {


    private String[] title={"全部","待支付","已支付","已入住","已取消"};
    private int[] orderStateIdTitle={0,1,2,3,5};


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.fragment_order,container,false);

        //保证方法可以获取到上下文
        if (getActivity()==null){
            return view;
        }

        //获取控件
        TabLayout tlOrderTitle=view.findViewById(R.id.tl_order_title);
        ViewPager2 vpOrderContainer=view.findViewById(R.id.vp_order_container);

        //实例化
        MyFragmentStateAdaper myFragmentStateAdaper=new MyFragmentStateAdaper(getActivity());
        //设置适配器
        vpOrderContainer.setAdapter(myFragmentStateAdaper);
        //设置预加载数
        vpOrderContainer.setOffscreenPageLimit(1);
        //建立关联
        new TabLayoutMediator(tlOrderTitle, vpOrderContainer, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                //设置显示
                tab.setText(title[position]);
            }
        }).attach();


        return view;
    }

    class MyFragmentStateAdaper extends FragmentStateAdapter{

        //存放fragment
        Fragment[] fragments;

        public MyFragmentStateAdaper(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
            fragments=new Fragment[title.length];
        }


        @NonNull
        @Override
        public Fragment createFragment(int position) {

            if (fragments[position]==null){


                //创建传递参数
                Bundle bundle=new Bundle();
                bundle.putInt("orderStateId",orderStateIdTitle[position]);


                //创建fragment
                OrderListFragment orderListFragment=new OrderListFragment();
                orderListFragment.setArguments(bundle);
                fragments[position]=orderListFragment;
            }


            return fragments[position];
        }

        //获取fragment数量
        @Override
        public int getItemCount() {
            return fragments.length;
        }
    }
}
